package net.cmkj.mine.common.controller;

import java.util.LinkedHashMap;

import com.jfinal.core.ActionException;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.render.RenderManager;

import net.cmkj.mine.util.CommonUtils;
/**
 * 
 * @author zzcmkj
 *
 */
public abstract class BaseController extends Controller {
	public static final int BUFFER_SIZE = 1024 * 1024;
	/**
	 * 获取排序对象
	 * @author zzcmkj	
	 * @return
	 */
	protected LinkedHashMap<String,String> getOrderby(){
		String sort=this.getPara("sort");
		String order=this.getPara("order");
		LinkedHashMap<String,String> orderby=new LinkedHashMap<String,String>();
		if(CommonUtils.isNotEmpty(sort)){
			orderby.put(sort, order);
		}
		return orderby;
	}
	/**
	 * 获取排序字符串
	 * @author zzcmkj	
	 * @return
	 */
	protected String getOrderbyStr(){
		String sort=this.getPara("sort");
		String order=this.getPara("order");
		if(CommonUtils.isNotEmpty(sort)){
			if(CommonUtils.isNotEmpty(order)){
				return " order by "+ sort+" "+order;
			}else{
				return " order by "+ sort+" desc";
			}
		}
		return " order by id desc";
	}
	/**
	 * 获取每几页
	 * @author zzcmkj	
	 * @return
	 */
	protected int getPage(){
		return this.getParaToInt("page", 1);
	}
	/**
	 * 获取每页数量
	 * @author zzcmkj	
	 * @return
	 */
	protected int getRows(){
		int rows=this.getParaToInt("limit", 10);
		if(rows>1000)rows=1000;
		return rows;
	}
	
	private Double toDouble(String value, Double defaultValue) {
		try {
			if (StrKit.isBlank(value)) {
				return defaultValue;
			}
			value = value.trim();
			value = value.replaceAll(",", "");
			return Double.valueOf(value);
		} catch (Exception e) {
			throw new ActionException(400, RenderManager.me().getRenderFactory().getErrorRender(400),  "Can not parse the parameter \"" + value + "\" to Double value.");
		}
	}
	
	public Double getParaToDouble(String name, Double defaultValue) {
		return toDouble(getRequest().getParameter(name), defaultValue);
	}
	
	private Float toFloat(String value, Float defaultValue) {
		try {
			if (StrKit.isBlank(value)) {
				return defaultValue;
			}
			value = value.trim();
			value = value.replaceAll(",", "");
			return Float.valueOf(value);
		} catch (Exception e) {
			throw new ActionException(400, RenderManager.me().getRenderFactory().getErrorRender(400),  "Can not parse the parameter \"" + value + "\" to Double value.");
		}
	}
	
	public Float getParaToFloat(String name, Float defaultValue) {
		return toFloat(getRequest().getParameter(name), defaultValue);
	}
	
}






